package com.jakewharton.rxbinding2.widget;

import com.jakewharton.rxbinding2.InitialValueObservable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import ohos.agp.components.SearchBar;

import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class SearchBarQueryTextChangesObservable extends InitialValueObservable<CharSequence> {
  private final SearchBar view;

  SearchBarQueryTextChangesObservable(SearchBar view) {
    this.view = view;
  }

  @Override protected void subscribeListener(Observer<? super CharSequence> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, observer);
    view.setQueryListener(listener);
    observer.onSubscribe(listener);
  }

  @Override protected CharSequence getInitialValue() {
    return view.getQuery();
  }

  static final class Listener extends MainThreadDisposable implements SearchBar.QueryListener {
    private final SearchBar view;
    private final Observer<? super CharSequence> observer;

    public Listener(SearchBar view, Observer<? super CharSequence> observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override protected void onDispose() {
      view.setQueryListener(null);
    }

    @Override
    public boolean onQuerySubmit(String s) {
      return false;
    }

    @Override
    public boolean onQueryChanged(String s) {
      if (!isDisposed()) {
        observer.onNext(s);
        return true;
      }
      return false;
    }
  }
}
